﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Param = ClassLibrary.Parameters.Values;
using System.IO;
using ClassLibrary;
using System.Diagnostics;
using System.Resources;

namespace ControlLibrary
{
    public partial class Panel_GenerateThumb : UserControl
    {
        int ow, oh; //orignial image weight/height
        private enum ThumbType
        {
            medium,
            small
        }

        public delegate void OnGenerateSmall(bool succeed, string imgPath, decimal width, decimal height);
        [Category("Configuration"), Browsable(true), Description("")]
        public event OnGenerateSmall onGenerateSmall;

        /*public delegate void OnButtonGenerateStateChanged(bool enable);
        [Category("Configuration"), Browsable(true), Description("")]
        public event OnButtonGenerateStateChanged onButtonGenerateStateChanged;*/

        public delegate void OnGenerateMedium(bool succeed, string imgPath, decimal width, decimal height);
        [Category("Configuration"), Browsable(true), Description("")]
        public event OnGenerateMedium onGenerateMedium;

        public delegate void OnPathDefined();
        [Category("Configuration"), Browsable(true), Description("")]
        public event OnPathDefined onPathDefined;

        #region CONSTRUCTOR
        public Panel_GenerateThumb()
        {
            InitializeComponent();
            //Init();
        }
        #endregion

        public void UpdateUI()
        {
            ResourceManager _RM = new ResourceManager("ControlLibrary.Panel_GenerateThumb", typeof(Panel_Marker).Assembly);
            try
            {
                textBox_ImagePath.CueText = _RM.GetString("textBox_ImagePath.CueText");
                label_error.Text = _RM.GetString("label_error.Text");
                label_res.Text = _RM.GetString("label_res.Text");
                label1.Text = _RM.GetString("label1.Text");
                label2.Text = _RM.GetString("label2.Text");
                label8.Text = _RM.GetString("label8.Text");
                label4.Text = _RM.GetString("label4.Text");
            }
            catch (Exception e)
            {
                ErrorManager.WriteLog("Panel_GenerateThumb", "UpdateUI", e, Param.RM.GetString("MB_Error_UpdateUI"));
            }
        }

        public void Init(decimal MediumWidth, decimal MediumHeight, decimal SmallWidth, decimal SmallHeight)
        {

            try
            {
                if (MediumWidth < numericUpDown_MediumWidth.Minimum || MediumWidth > numericUpDown_MediumWidth.Maximum)
                    numericUpDown_MediumWidth.Value = Param.Default_MediumWidth;
                else numericUpDown_MediumWidth.Value = MediumWidth;

                if (MediumHeight < numericUpDown_MediumHeight.Minimum || MediumHeight > numericUpDown_MediumHeight.Maximum)
                    numericUpDown_MediumHeight.Value = Param.Default_MediumHeight;
                else numericUpDown_MediumHeight.Value = MediumHeight;

                if (SmallWidth < numericUpDown_SmallWidth.Minimum || SmallWidth > numericUpDown_SmallWidth.Maximum)
                    numericUpDown_SmallWidth.Value = Param.Default_SmallHeight;
                else numericUpDown_SmallWidth.Value = SmallWidth;

                if (SmallHeight < numericUpDown_SmallHeight.Minimum || SmallHeight > numericUpDown_SmallHeight.Maximum)
                    numericUpDown_SmallHeight.Value = Param.Default_SmallHeight;
                else numericUpDown_SmallHeight.Value = SmallHeight;

                string myPicturesFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);

                /*_myDocFolder = Parametres.Values.myDocFolder;
                _myDocSmallFolder = Parametres.Values.myDocSmallFolder;
                _myDocMediumFolder = Parametres.Values.myDocMediumFolder;*/



                if (!Directory.Exists(Param.localPath_Small))
                    Directory.CreateDirectory(Param.localPath_Small);

                if (!Directory.Exists(Param.localPath_Medium))
                    Directory.CreateDirectory(Param.localPath_Medium);

                textBox_ImagePath.Text = string.Empty;
                textBox_Small.Text = string.Empty;
                textBox_Medium.Text = string.Empty;

                label_res.Visible = false;
                label_error.Visible = false;

                if (!File.Exists(Param.localPath_nConvert))
                {
                    setEnable(false);
                    throw new Exception("nConvert not found");
                }

                /*if (null != onButtonGenerateStateChanged)
                    onButtonGenerateStateChanged(false);*/

                if (Directory.Exists(Param.localPath_picturesLibrary))
                    openFileDialog1.InitialDirectory = Param.localPath_picturesLibrary;
                else if (Directory.Exists(myPicturesFolder))
                    openFileDialog1.InitialDirectory = myPicturesFolder;
            }
            catch (Exception e)
            {
                ErrorManager.WriteLog("Panel_GenerateThumb", "init", e, e.Message);
            }
        }

        public void Convert()
        {
            bool RC = false;
            try
            {
                if (File.Exists(Param.localPath_nConvert))
                {
                    RC = Convert(ThumbType.small);
                    if (true == RC)
                        RC = Convert(ThumbType.medium);
                    else throw new Exception("Convert(ThumbType) failed");
                }
                else
                    throw new Exception("nconvert.exe not found");
            }
            catch (Exception e)
            {
                ErrorManager.WriteLog("Panel_GenerateThumb", "init", e, e.Message);
            }
        }

        private bool Convert(ThumbType type)
        {
            string imagePath = string.Empty;
            bool RC = true;
            try
            {
                string arg;
                string extension = ".jpg";
                decimal W, H;

                if (type == ThumbType.small)
                {
                    imagePath = Path.Combine(Param.localPath_Small, textBox_Small.Text + "_small" + extension);

                    W = numericUpDown_SmallWidth.Value;
                    H = numericUpDown_SmallHeight.Value;
                }
                else
                {
                    imagePath = Path.Combine(Param.localPath_Medium, textBox_Medium.Text + "_med" + extension);

                    W = numericUpDown_MediumWidth.Value;
                    H = numericUpDown_MediumHeight.Value;
                }



                //Background of the canva
                int r = 223;
                int g = 223;
                int b = 223;
                decimal cw = 4m; // border width 

                /*arg = " -overwrite -resize " + (W - cw) + " " + (H - cw) + " -ratio -bgcolor "+r+" "+g+" "+b+" -canvas " + W + " " + H + " center -o \"" +
                imagePath + "\" \"" + textBox_ImagePath.Text + "\"";*/

                if (type == ThumbType.small)
                {
                    arg = " -overwrite -resize " + (W - cw) + " " + (H - cw) + " -bgcolor " + r + " " + g + " " + b + " -canvas " + W + " " + H + " center -o \"" +
                    imagePath + "\" \"" + textBox_ImagePath.Text + "\"";
                }
                else
                {
                    arg = " -overwrite -resize " + (W - cw) + " " + (H - cw) + " -ratio -bgcolor "+r+" "+g+" "+b+" -canvas " + W + " " + H + " center -o \"" +
                    imagePath + "\" \"" + textBox_ImagePath.Text + "\"";
                }


                /*arg = " -overwrite -resize " + (W - cw) + " " + (H - cw) + " -canvas " + W + " " + H + " center -bgcolor " + r + " " + g + " " + b + " -ratio" + " -o \"" +
                        imagePath + "\" \"" + textBox_ImagePath.Text + "\"";*/

                /*arg = " -overwrite -resize " + L + " " + H + " -ratio" + " -o \"" +
                        imagePath + "\" \"" + textBox_ImagePath.Text + "\"";*/



                //Script execution
                Process nConvert = new Process();
                string file = "\"" + Param.localPath_nConvert + "\"";
                ProcessStartInfo nConvertInfo = new ProcessStartInfo(file, arg);

                nConvertInfo.UseShellExecute = false;
                nConvertInfo.RedirectStandardError = true;
                nConvert.StartInfo = nConvertInfo;
                nConvertInfo.CreateNoWindow = true;

                nConvert.Start();

                StreamReader sr = nConvert.StandardError;
                string s = sr.ReadLine();
                nConvert.WaitForExit();
                nConvert.Close();

                if (!s.EndsWith("OK"))
                {
                    label_error.Visible = true;
                    label_res.Visible = false;
                    throw new Exception(s + "\n" + file + "\n" + arg+" \nconvertion failed");
                }
                else if (!File.Exists(imagePath))
                {
                    label_error.Visible = true;
                    label_res.Visible = false;
                    throw new Exception(file + "\n" + arg + "\n"+imagePath + " file not found");
                }
                else
                {
                    label_res.Visible = true;
                    label_error.Visible = false;
                    return RC;
                }
            }
            catch (Exception e)
            {
                RC = false;
                ErrorManager.WriteLog("EditGenererImage.cs", "Convert", e, "Convertion failed");
                return RC;
            }
            finally
            {
                if (type == ThumbType.small && null != onGenerateSmall)
                    onGenerateSmall(RC, imagePath, numericUpDown_SmallWidth.Value, numericUpDown_SmallHeight.Value);
                else if (type == ThumbType.medium && null != onGenerateMedium)
                    onGenerateMedium(RC, imagePath, numericUpDown_MediumWidth.Value, numericUpDown_MediumHeight.Value);
            }
        }

        private void setEnable(bool value)
        {
            textBox_ImagePath.Enabled = value;
            textBox_Medium.Enabled = value;
            textBox_Small.Enabled = value;

            numericUpDown_SmallHeight.Enabled = value;
            numericUpDown_MediumHeight.Enabled = value;
            numericUpDown_SmallWidth.Enabled = value;
            numericUpDown_MediumWidth.Enabled = value;

            button_Browse.Enabled = value;
        }

        private void textBox_ImagePath_TextChanged(object sender, EventArgs e)
        {
            try
            {
                if (textBox_ImagePath.Text != string.Empty && File.Exists(textBox_ImagePath.Text))
                {
                    FileInfo fifo = new FileInfo(textBox_ImagePath.Text);
                    textBox_Small.Text = fifo.Name.Replace(fifo.Extension, "");

                    Image img = new Bitmap(textBox_ImagePath.Text);
                    ow = img.Width;
                    oh = img.Height;


                }
            }
            catch (Exception ex)
            {
                ErrorManager.WriteLog("Panel_GenerateThumb", "textBox_ImagePath_TextChanged", ex);
            }
        }

        private void button_Browse_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
            {
                textBox_ImagePath.Text = openFileDialog1.FileName;
                Param.localPath_picturesLibrary = Path.GetDirectoryName(openFileDialog1.FileName);
                if (null != onPathDefined)
                    onPathDefined();
            }
        }

        private void textBox_small_TextChanged(object sender, EventArgs e)
        {
            textBox_Medium.Text = textBox_Small.Text;
        }

        private void textBox_InfoBulle_TextChanged(object sender, EventArgs e)
        {
            textBox_Small.Text = textBox_Medium.Text;
        }

        private void checkBox_Proportion_CheckedChanged(object sender, EventArgs e)
        {
            if (!checkBox_Proportion.Checked)
                checkBox_Proportion.Image = Properties.Resources.Proportion2;
            else
                checkBox_Proportion.Image = Properties.Resources.Proportion1;
        }

    }
}
